package org.example.cloudnativelab.aspect;

import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Counter;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;

@Aspect
@Component
public class QpsAspect {
    private final MeterRegistry meterRegistry;
    private final ConcurrentHashMap<String, Counter> counters = new ConcurrentHashMap<>();

    public QpsAspect(MeterRegistry meterRegistry) {
        this.meterRegistry = meterRegistry;
    }

    @AfterReturning("execution(* org.example.cloudnativelab.controller..*(..))")
    public void afterReturning(JoinPoint joinPoint) {
        String methodName = joinPoint.getSignature().getName();
        String className = joinPoint.getSignature().getDeclaringTypeName();
        String counterName = className + "." + methodName;

        // Get counter or create new counter
        Counter counter = counters.computeIfAbsent(counterName, name ->
                Counter.builder(name)
                        .description("QPS of " + name)
                        .register(meterRegistry)
        );
        counter.increment();
    }
}
